package cn.sciento.boot.api.customize.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import org.apache.commons.lang3.StringUtils;

public class ParamUtil {
  public static Map<String, Object> parseParams(String argKeys, Object... args) {
    HashMap<String, Object> params = new HashMap<>();
    if (StringUtils.isNotBlank(argKeys)) {
      String[] keys = argKeys.split(",");
      for (int i = 0; i < keys.length; i++)
        params.put(keys[i], args[i]); 
    } 
    return params;
  }
  
  public static String parseParamsKey(CtMethod targetMethod) {
    List<String> argKeys = new ArrayList<>();
    MethodInfo methodInfo = targetMethod.getMethodInfo();
    CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
    LocalVariableAttribute attr = (LocalVariableAttribute)codeAttribute.getAttribute("LocalVariableTable");
    try {
      if (attr != null) {
        int len = (targetMethod.getParameterTypes()).length;
        int pos = Modifier.isStatic(targetMethod.getModifiers()) ? 0 : 1;
        for (int i = pos; i < len; i++)
          argKeys.add(attr.variableName(i)); 
      } 
    } catch (NotFoundException e) {
      e.printStackTrace();
    } 
    return StringUtils.join(argKeys, ",");
  }
  
  public static String replaceSpecialChar(String str) {
    return 
      StringUtils.replaceAll(str, "\"", "\\\\\"")
      .replaceAll("\r", "\\\\r")
      .replaceAll("\n", "\\\\n");
  }
}
